package com.gitee.hermer.engine.jars.core.orm.ibatis.plugIn;

import java.util.Properties;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;

import com.gitee.hermer.engine.jars.core.orm.ex.OptimisticLockException;

@Intercepts({@org.apache.ibatis.plugin.Signature(type=org.apache.ibatis.executor.Executor.class, method="update", args={MappedStatement.class, Object.class})})
public class MybaticOptimisticPlugIn implements Interceptor{

	public Object intercept(Invocation invocation)
			throws Throwable
	{
		MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];

		SqlCommandType type = mappedStatement.getSqlCommandType();
		int count = ((Integer)invocation.proceed()).intValue();
		if ((SqlCommandType.UPDATE == type) && 
				(count <= 0)) {
			throw new OptimisticLockException();
		}
		return Integer.valueOf(count);
	}

	public Object plugin(Object target)
	{
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {

	}

}
